$(() => {
    const token = GetQueryString("token");
    let page = 1;
    let pageSize = 5;
    let keywords = '';
    let area_code = '';
    let class_id = '';
    ajaxList(page);

    function ajaxList(page, keywords, area_code, class_id) {
        $.ajax({
            type: "post",
            url: url,
            data: { 'method': 'Forum|forum_list', 'page': page, 'pagelimit': pageSize, 'keywords': keywords, 'area_code': area_code, 'class_id': class_id, 'token': token },
            dataType: 'json',
            success: function(res) {
                // console.log(res);
                if (res.status == 1) {
                    let data = res.data.data;
                    let ads = res.data.ads;
                    let html = '';
                    let html1 = '';

                    data.forEach(item => {
                        // // console.log(item);
                        let date = getDate(item.create_time);
                        html += `
                        <li class="ringitem wrap${item.id}" data-id="${item.id}">`
                        if (item.company_confirm == 0) {
                            html += `<a href="./view/shop_details_personal.html?user_id=${item.user_id}&token=${token}" class="ringtop">`
                        } else {
                            html += `<a href="./view/shop_details_company.html?company_id=${item.company_id}&token=${token}" class="ringtop">`
                        }
                        html += `<img src="${item.head_logo == null ? 'img/orimg.png' : item.head_logo}" alt="" class="ringtpic" />
                                <div class="ringtco">
                                    <p class="ringtct1">${item.name}</p>`
                        if (item.level_logo != '') {
                            html += `<img src="${item.level_logo}" alt="${item.level_name}" class="userLevel"/>`
                        }
                        html += `</div>
                                <p class="ringtlr">${date}</p>
                            </a>
                            <p class="ringco">${item.content}</p>
                            <p class="slh">...</p>
                            <a href="javascript:;" class="ringco2">全文</a>
                            <div class="ringlilist">`
                        item.pictures.forEach((i, idx) => {
                            html += `
                                <a href="javascript:;"><img src="${i.thumb_url == '' ? 'img/banner.png' : i.thumb_url}" alt="${i.pic_name}" data-url="${i.pic_url}" data-idx="${idx}" class="rilipic plusImg" /></a>
                            `
                        })
                        html += `
                            </div>
                            <div class="browse">
                                <p class="brot">${item.read_count}人浏览</p>
                                <div class="brolr">
                                    <a href="javascript:;" class="brolrlink commentClick" data-forum_id="${item.id}">
                                        <img src="img/brolrpic1.png" alt="" class="brolrpic" />
                                    </a>
                                    <a href="javascript:;" data-forum_id="${item.id}" class="brolrlink isDig" data-num="0" data-has_dig="${item.has_dig}">
                                        <span class="brolrpic brolrpic2"></span><span class="num">${item.digg_count}</span>
                                    </a>
                                </div>
                            </div>`
                        if (item.comments == "") {
                            html += '';
                        } else {
                            html += `<div class="brocomment">
                                <img src="img/brotop.png" alt="" class="brotop" /><div class="commentLists com${item.id}">`;
                            item.comments.forEach(p => {
                                html += `
                            <p class="brocoti"><a href="javascript:;" class="brocotlink">${p.nick_name}:</a>${p.content}</p>
                                    `;
                            })
                            html += `</div>`;
                        }
                        html += `</div>
                            <div class="inputBg comWrap${item.id}" >
                                <div class="commentWrap">
                                    <div class="commentInput">
                                        <input type="text" class="commentText" placeholder="请输入评论内容" /><button type="button" class="comSubmit">提交</button>
                                    </div>
                                </div>
                            </div>
                        </li>`;
                    });

                    ads.forEach(item => {
                        if (ads.length != 0) {
                            html1 += `
                            <a class="adsItem" href="${item.url + '&token=' + token}">
                                <img src="${item.img_url}" alt="${item.title}"style="width:100%;display:block;"/>
                            </a>
                        `;
                        }
                    })

                    if (data.length == 0 && ads.length == 0 && page == 1) {
                        $('.ringlist').css('margin', 'auto');
                    } else {
                        $('.ringlist').css('margin', '-1.4rem auto 0');
                    }
                    if (data.length < pageSize) {
                        $('.notMore').css('display', 'flex');
                    }
                    if (html != '') {
                        $('.ringlist').append(html + html1);
                    } else {
                        $('.ringlist').append(html1);
                    }

                    // 图片放大
                    $('.plusImg').on('click', function(e) {
                        e.stopPropagation();
                        let idx = e.target.dataset.idx;
                        let arr = [];
                        let img = $(this).attr('data-url');
                        $('.showImg').attr('src', img);
                        for (var i = 0; i < $(this).parent().parent().find("img").length; i++) {
                            arr.push($(this).parent().parent().find("img").eq(i).attr("data-url"));
                        }
                        let html = '';
                        arr.forEach(item => {
                            html += `
                            <div class="swiper-slide">
                                <img class="showImg" src="${item}" alt="">
                            </div>
                            `;
                        })
                        $('.swiper-wrapper').html(html);
                        // banner轮播
                        let plusSwiper = new Swiper('.swiper-container', {
                            // pagination: '.swiper-pagination',
                            paginationType: 'fraction',
                            observer: true,
                            observeParents: true,
                        })
                        $('.mask').css('background', 'black');
                        dialog('#plusImg');
                        $('.mask').css('z-index', '1001');
                        $('.mask').css('top', '0');
                        plusSwiper.slideTo(idx, false);
                    })

                    // 点赞高亮
                    for (let i = 0; i < $('.isDig').length; i++) {
                        if ($('.isDig').eq(i).attr('data-has_dig') == 1) {
                            $('.isDig').eq(i).addClass('on');
                        } else {
                            $('.isDig').eq(i).removeClass('on');
                        }
                    }

                    // 点赞
                    $('.isDig').on('click', function() {
                        let forum_id = $(this).attr('data-forum_id');
                        var _this = $(this);
                        $.ajax({
                            type: "post",
                            url: url,
                            data: { 'method': 'Forum|dig_or_not', 'forum_id': forum_id, 'token': token },
                            dataType: 'json',
                            success: function(res) {
                                // console.log(res);
                                if (res.status == 1) {
                                    $(_this).attr('data-num', res.data);
                                    let data_num = $(_this).attr('data-num');
                                    let num = $(_this).children(".num").html();
                                    if (data_num == 2) {
                                        $(_this).addClass('on');
                                        num++;
                                    } else {
                                        $(_this).removeClass('on');
                                        num--;
                                    }
                                    $(_this).children(".num").html(num);
                                }
                            }
                        })
                    })

                    // 文本溢出显示全文按钮
                    for (var i = 0; i < $(".ringco").length; i++) {
                        let width = $(".ringco").eq(i).width(); //div的宽度
                        let strLen = getBLen($(".ringco").eq(i).html());// 文本的字符串长度
                        let strWidth = strLen * 7.5;
                        let endWidth = strWidth / width;
                        console.log(endWidth > 2);
                        if (endWidth > 2) {
                            console.log('大2')
                            $('.ringco2').eq(i).show();
                            $('.slh').eq(i).show();
                        } else {
                            $('.ringco2').eq(i).hide();
                            $('.slh').eq(i).hide();
                        }
                    }

                    // 点击全文显示
                    $('.ringco2').on('click', function() {
                        $(this).parent().find(".ringco").css('height', 'auto');
                        $(this).parent().find('.slh').hide();
                        $(this).hide();
                    })

                } else if (res.status == 2) {
                    location.href = "fox://logout";
                } else {
                    alert(res.message);
                }
            }
        });
    }

    // window.setTimeout(function(e) {
    //     e.$el[0].scrollIntoViewIfNeeded();
    // }, 200);

    $(document).scroll(function() {
        toppp = $(document).scrollTop();
    })


    // ios聚焦输入框浮于键盘顶部方法
    $('.commentText').focus(function() {
        setTimeout(function() {
            document.body.scrollTop = document.body.scrollHeight;
        })
    })

    $('.commentText').blur(function() {
        $('.inputBg').hide();
    })

    // 添加评论
    $(document).on('click', '.commentClick', function(e) {
        let forum_id = $(this).attr('data-forum_id');
        $('.forum_id').attr('data-forum_id', forum_id);
        e.stopPropagation();
        $('.comWrap' + forum_id).show().parent().siblings().find('.inputBg').hide();
        $('.comWrap' + forum_id).find('.commentText').focus();
    })

    // 提交评论
    $(document).on('click', '.comSubmit', function() {
        console.log(111);
        let forum_id = $('.forum_id').attr('data-forum_id');
        console.log(forum_id);
        let content = $('.comWrap' + forum_id).find('.commentText').val();
        console.log(content);
        $.ajax({
            type: "post",
            url: url,
            data: { 'method': 'Forum|review', 'forum_id': forum_id, 'token': token, 'content': content },
            dataType: 'json',
            success: function(res) {
                console.log(res)
                if (res.status == 1) {
                    let data = res.data;
                    $('.comWrap' + forum_id).hide();
                    $('.commentText').val('');
                    let html = '';
                    html = `
                    <p class="brocoti"><a href="javascript:;" class="brocotlink">${data.nick_name}:</a>${data.content}</p>
                    `;
                    console.log($('.com' + forum_id).length);
                    if ($('.com' + forum_id).length == 0) {
                        let wrap = '';
                        wrap = `
                        <div class="brocomment">
                            <img src="img/brotop.png" alt="" class="brotop">
                            <div class="commentLists com${forum_id}"></div>
                        </div>
                        `;
                        $('.wrap' + forum_id).append(wrap);
                    }
                    $(".com" + forum_id).append(html);
                    // $('.ringlist').html('');
                    // ajaxList(page);
                } else if (res.status == 2) {
                    location.href = "fox://logout";
                } else {
                    alert(res.message);
                }
            }
        })
    })

    //查看更多评论列表
    // $(document).on("click", ".moreBtn", function() {
    //     let forum_id = $(this).attr('data-id');
    //     let _this = $(this);
    //     $.ajax({
    //         type: "post",
    //         url: url,
    //         data: { 'method': 'Forum|more_comments', 'forum_id': forum_id },
    //         dataType: 'json',
    //         success: function(res) {
    //             console.log(res);
    //             let data = res.data;
    //             let html = '';
    //             if (res.status == 1) {
    //                 if (data) {
    //                     data.forEach(item => {
    //                         html += `
    //                         <p class="brocoti"><a href="javascript:;" class="brocotlink">${item.nick_name}:</a>${item.content}</p>
    //                     `
    //                     })
    //                     $(_this).prev().append(html);
    //                 }
    //             } else if (res.status == 2) {
    //                 location.href = "fox://logout";
    //             } else {
    //                 alert(res.message);
    //             }
    //         }
    //     })
    // })

    // 分类
    $.ajax({
        type: "post",
        url: url,
        data: { 'method': 'Forum|get_category_by_level', 'level': 2 },
        dataType: 'json',
        success: function(res) {
            // // console.log(res);
            if (res.status == 1) {
                let data = res.data;
                let html = '';
                for (let i in data) {
                    let o = data[i];
                    if (i < 5) {
                        html += `
                            <a href="javascript:;" class="rinalink" data-id='${o.id}'><span>${o.bname}</span></a>
                        `;
                    }
                }
                let list = '';
                let all = '';
                all = `
                <a href="javascript:;" class="diarlink" data-id=''>全部</a>
                `;
                data.forEach(item => {
                    list += `
                        <a href="javascript:;" class="diarlink" data-id='${item.id}'>${item.bname}</a>
                    `;
                })
                $('.rinav_c').html(html);
                $('.diarin').html(all + list);
            } else if (res.status == 2) {
                location.href = "fox://logout";
            } else {
                alert(res.message);
            }
        }
    })

    $('.ringlink').on('click', function() {
        if (token) {
            // location.href = "view/ring_add.html?token=" + token;
            location.href = 'fox://publish';
        } else {
            location.href = "fox://logout";
        }
    })

    //下拉导航点击高亮
    $(document).on('click', ".diarin .diarlink", function() {
        $(this).addClass("on").siblings(".diarlink").removeClass("on");
        let class_id = $(this).attr('data-id');
        $('.class_id').attr('data-class_id', class_id);
        // console.log(class_id);
        $('.rinalink').removeClass('on');
        page = 1;
        $('.ringlist').html('');
        $('.notMore').css('display', 'none');
        let area_code = $('.area_code').attr('data-area_code');
        if (area_code) {
            ajaxList(page, '', area_code, class_id);
        } else {
            ajaxList(page, '', '', class_id);
        }
        dialogClose();
    })
    $(document).on('click', '.rinalink', function() {
        $(this).addClass('on').siblings().removeClass('on');
        let class_id = $(this).attr('data-id');
        $('.class_id').attr('data-class_id', class_id);
        // console.log(class_id);
        if (class_id == '') {
            ajaxList(page, '', '', '');
        }
        page = 1;
        $('.ringlist').html('');
        $('.notMore').css('display', 'none');
        let area_code = $('.area_code').attr('data-area_code');
        if (area_code) {
            ajaxList(page, '', area_code, class_id);
        } else {
            ajaxList(page, '', '', class_id);
        }
        $('.diarlink').removeClass('on');
    })

    // 城市列表
    //城市图标翻转效果
    $(".inhetoplr").on('click', function() {
        $.ajax({
            type: "post",
            url: url,
            data: { 'method': 'Api|get_area_list', 'pcode': 1 },
            dataType: 'json',
            success: function(res) {
                // console.log(res);
                if (res.status == 1) {
                    let html = '';
                    let data = res.data;
                    let all = '';
                    all = `
                    <a href="javascript:;" class="shList areaItem" data-area_code="">全部</a>
                    `;
                    data.forEach(item => {
                        html += `<a href="javascript:;" class="shList areaItem" data-area_code="${item.area_code}">${item.area_name}</a>`
                    })
                    $('.areaLists').html(all + html);
                    $('.areaItem').on('click', function() {
                        dialogClose();
                        $(this).addClass("on").siblings(".shList").removeClass("on");
                        $(".inhetoplr").attr("data-num", 1).removeClass("on");
                        let area_code = $(this).attr('data-area_code');
                        $('.area_code').attr('data-area_code', area_code);
                        $('.ringlist').html('');
                        $('.notMore').css('display', 'none');
                        page = 1;
                        if (area_code == '') {
                            $('#inhe').html('地区');
                        } else {
                            $('#inhe').html($(this).html());
                        }
                        let class_id = $('.class_id').attr('data-class_id');
                        if (class_id) {
                            ajaxList(page, '', area_code, class_id);
                        } else {
                            ajaxList(page, '', area_code, '');
                        }
                    })
                } else if (res.status == 2) {
                    location.href = "fox://logout";
                } else {
                    alert(res.message);
                }
            }
        })
    })

    // 搜索
    $('.inheinputd').on('submit', function(e) {
        e.preventDefault();
        let keys = $('.heinput').val();
        $('.keys').attr('data-keys', keys);
        $('.ringlist').html('');
        $('.notMore').css('display', 'none');
        page = 1;
        ajaxList(page, keys, '', '');
        $('.heinput').val("");
    })



    // 下拉加载更多
    $(window).scroll(function() {
        if ($(document).scrollTop() >= $(document).height() - $(window).height() - 1) {
            // console.log('我到底了');
            if ($('.notMore').css('display') != "flex") {
                page++;
                let area_code = $('.area_code').attr('data-area_code');
                let class_id = $('.class_id').attr('data-class_id');
                let keys = $('.keys').attr('data-keys');
                if (area_code || class_id || keys) {
                    ajaxList(page, keys, area_code, class_id);
                } else {
                    ajaxList(page);
                }
            }
        }
    })
})